import 'package:objectbox/objectbox.dart';
import '../../../lib_database.dart';
import '../basemodel.dart';
import '../../network.dart';
import '../../../objectbox.g.dart';

@Entity()
class NodeInfo {
  @Id()
  int id = 0;
  String chain;
  String url;
  String? name;
  bool isSelected;
  String? rate;
  String? blockHeight;

  NodeInfo(
      {this.id = 0,
      required this.chain,
      this.rate = '0',
      this.blockHeight = '0',
      required this.url,
      this.name,
      this.isSelected = false});

  @override
  String toString() {
    return 'NodeInfo(name: $name, chain: $chain, url: $url, isSelected: $isSelected, id: $id, rate: $rate, blockHeight: $blockHeight)';
  }
}

class NodeInfoModel extends BaseModel<NodeInfo> {
  NodeInfoModel(Box<NodeInfo> box) : super(box);

  //根据chain来查对应的node
  List<NodeInfo> getNodeInfoList(String chain) {
    return box.query(NodeInfo_.chain.equals(chain)).build().find();
  }

  //根据chain来查选中的node,这个一定要有
  NodeInfo getSelectedNodeInfo(String chain) {
    var info = box
        .query(
            NodeInfo_.chain.equals(chain) & NodeInfo_.isSelected.equals(true))
        .build()
        .findFirst();
    if (info != null) {
      return info;
    } else {
      //如果没有选中的节点，这里重新处理选中第一条
      var autoSelectInfo =
          box.query(NodeInfo_.chain.equals(chain)).build().findFirst();
      autoSelectInfo!.isSelected = true;

      updateNodeInfo(autoSelectInfo);
      return autoSelectInfo;
    }
  }

  //根据节点来查对应的nodeInfo
  NodeInfo? getNodeInfo(String url) {
    return box.query(NodeInfo_.url.equals(url)).build().findFirst();
  }

  //删除节点信息
  deleteNodeInfo(NodeInfo nodeInfo) {
    box.remove(nodeInfo.id);
  }

  deleteAllNodeInfo(String chain) {
    List<NodeInfo>? nodeInfoList =
        box.query(NodeInfo_.chain.equals(chain)).build().find();
    for (var element in nodeInfoList) {
      box.remove(element.id);
    }
  }

  //添加节点, 并返回被添加的节点
  Future<NodeInfo> addNodeInfo(
      {required String chain,
      required String url,
      String? name,
      bool isSelected = false}) async {
    var nodeInfo =
        NodeInfo(chain: chain, url: url, name: name, isSelected: isSelected);
    await box.putAsync(nodeInfo, mode: PutMode.insert);

    return nodeInfo;
  }

  //更新节点数据节点
  int updateNodeInfo(NodeInfo info) {
    return box.put(info, mode: PutMode.update);
  }

  //更新节点数据节点
  Future<int> updateNodeInfoAsync(NodeInfo info) {
    return box.putAsync(info, mode: PutMode.update);
  }

  //初始化节点
  initNode() async {
    for (Chain c in ChainList().chains) {
      List<String> rpcList = c.evmInfo!.rpcList;
      if (rpcList.isEmpty) {
        continue;
      }
      var infoList = box
          .query(NodeInfo_.chain.equals(c.shortName))
          .build()
          .find()
          .toList();
      //转为url列表
      List<String> nodeURLs = infoList.map((e) {
        return e.url;
      }).toList();
      for (var node in rpcList) {
        if (nodeURLs.length == 0 || !nodeURLs.contains(node)) {
          await addNodeInfo(chain: c.shortName, url: node);
        }
      }
      //查找是否有选中的节点
      var selectedInfo = box
          .query(NodeInfo_.chain.equals(c.shortName) &
              NodeInfo_.isSelected.equals(true))
          .build()
          .findFirst();

      // 没有的话就拿第一个
      if (selectedInfo == null) {
        selectedInfo =
            box.query(NodeInfo_.chain.equals(c.shortName)).build().find().first;
        selectedInfo.isSelected = true;
        ObjectBox().nodeInfoModel.updateNodeInfo(selectedInfo);
      }
    }
  }

// //设置节点信息，并返回选中的节点
// String _setNodeInfo(String chain, List<String> nodes) {
//   //插入节点信息
//   nodes.forEach((element) {
//     var info = ObjectBox().nodeInfoModel.getNodeInfo(element);
//     if (info == null) {
//       ObjectBox().nodeInfoModel.addNodeInfo(chain: chain, url: element);
//     }
//   });
//   //查找是否有选中的节点
//   var selectedNode = nodes.firstWhere((element) {
//     var info = ObjectBox().nodeInfoModel.getNodeInfo(element);
//     return info?.isSelected == true;
//   }, orElse: () => '');
//   //没有的话就拿第一个
//   if (selectedNode == '') {
//     selectedNode = nodes[0];
//     var unSelectedInfo = ObjectBox().nodeInfoModel.getNodeInfo(nodes[0]);
//     unSelectedInfo!.isSelected = true;
//     ObjectBox().nodeInfoModel.updateNodeInfo(unSelectedInfo);
//   }

//   return selectedNode;
// }
}

// @Entity()
// class NodeList {
//   @Id()
//   int id = 0;
//   String chain;

//   List<String> nodes;

//   NodeList({this.id = 0, required this.chain, required this.nodes});

//   String getDisplayChain() {
//     return chain.startsWith(Config.customChainShortNamePrefix)
//         ? chain.substring(Config.customChainShortNamePrefix.length)
//         : chain;
//   }
// }

// class NodeListModel extends BaseModel<NodeList> {
//   NodeListModel(Box<NodeList> box) : super(box);

//   deleteNode(String chainShortName) {
//     List<int> nodeIdList =
//         box.query(NodeList_.chain.equals(chainShortName)).build().findIds();

//     ObjectBox().nodeInfoModel.deleteAllNodeInfo(chainShortName);
//     box.removeMany(nodeIdList);
//   }

//   List<NodeList> getAllNodeList() {
//     return box.getAll();
//   }

//   //根据chain来查对应的node
//   NodeList? getNodeList(Chain c) {
//     return box.query(NodeList_.chain.equals(c.shortName)).build().findFirst();
//   }

//   //插入一个节点
//   addNode(Chain c, String url, {isSelected = true}) {
//     NodeList? node =
//         box.query(NodeList_.chain.equals(c.shortName)).build().findFirst();
//     if (node != null) {
//       node.nodes.add(url);
//       ObjectBox().nodeInfoModel.addNodeInfo(chain: c.shortName, url: url);
//       box.put(node, mode: PutMode.update);
//     }
//   }

//   //删除一个节点
//   removeNode(Chain c, String url) {
//     NodeList? node =
//         box.query(NodeList_.chain.equals(c.shortName)).build().findFirst();

//     if (node?.nodes.remove(url) == true) {
//       ObjectBox().nodeInfoModel.deleteNodeInfo(url);
//       box.put(node!, mode: PutMode.update);
//     }
//   }

//   //初始化节点
//   initNode() {
//     for (Chain c in ChainList().chains) {
//       NodeList? node =
//           box.query(NodeList_.chain.equals(c.shortName)).build().findFirst();

//       List<String>? rpcList;
//       if (c.type == ChainType.eth) {
//         rpcList = c.evmInfo!.rpcList;
//       } else if (c.type == ChainType.tron) {
//         rpcList = ['https://api.trongrid.io'];
//       }

//       if (null == rpcList || rpcList.isEmpty) {
//         continue;
//       }

//       if (null == node) {
//         //初始化，导入节点数据

//         _setNodeInfo(c.shortName, rpcList);
//         box.put(NodeList(chain: c.shortName, nodes: rpcList),
//             mode: PutMode.insert);
//       } else {
//         //已经导入过节点，检测是否有新的节点添加
//         bool needUpdate = false;

//         for (String r in rpcList) {
//           if (!node.nodes.contains(r)) {
//             node.nodes.add(r);
//             //没有的话就添加节点信息
//             var info = ObjectBox().nodeInfoModel.getNodeInfo(r);
//             if (info == null) {
//               ObjectBox().nodeInfoModel.addNodeInfo(chain: c.shortName, url: r);
//             }
//             needUpdate = true;
//           }
//         }
//         if (needUpdate) {
//           box.put(node, mode: PutMode.update);
//         }
//       }
//     }
//   }

//   //设置节点信息，并返回选中的节点
//   String _setNodeInfo(String chain, List<String> nodes) {
//     //插入节点信息
//     nodes.forEach((element) {
//       var info = ObjectBox().nodeInfoModel.getNodeInfo(element);
//       if (info == null) {
//         ObjectBox().nodeInfoModel.addNodeInfo(chain: chain, url: element);
//       }
//     });
//     //查找是否有选中的节点
//     var selectedNode = nodes.firstWhere((element) {
//       var info = ObjectBox().nodeInfoModel.getNodeInfo(element);
//       return info?.isSelected == true;
//     }, orElse: () => '');
//     //没有的话就拿第一个
//     if (selectedNode == '') {
//       selectedNode = nodes[0];
//       var unSelectedInfo = ObjectBox().nodeInfoModel.getNodeInfo(nodes[0]);
//       unSelectedInfo!.isSelected = true;
//       ObjectBox().nodeInfoModel.updateNodeInfo(unSelectedInfo);
//     }

//     return selectedNode;
//   }
// }
